package com.wujie.hello.spring.cloud.zuul.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author wujie
 * @version 1.0.0:
 * @title LoginFilter 自定义网关过滤器
 * @Description TODO
 * @dateTime 2020/9/4 21:01
 * @Copyright 2020-2021
 */
@Component
public class LoginFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
    /**
     * 配置过滤类型，有四种不同生命周期的过滤器类型
     * 1. pre：路由之前
     * 2. routing：路由之时
     * 3. post：路由之后
     * 4. error：发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }
    /**
     * 配置过滤的顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }
    /**
     * 配置是否需要过滤：true/需要，false/不需要
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }
    /**
     * 过滤器的具体业务代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String auth = request.getHeader("auth");
        logger.info("{} >>> {}", request.getMethod(), request.getRequestURL().toString());
        if (!StringUtils.isNotBlank(auth)) {
            logger.warn("权限认证失败");
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.getResponse().setCharacterEncoding("UTF-8");
            context.getResponse().setContentType("text/html;cahrset=UTF-8");
            try {
                context.getResponse().getWriter().write("权限认证失败");
            } catch (IOException e) {
            }
        } else {
            logger.info("OK");
        }
        return null;
    }
}
